import React, {Component} from 'react'
import {
  Input,
  DatePicker,
  Button,
  Select,
  Modal,
  Form,
  Radio,
  message,
  Icon,
  Popover,
} from 'antd'
import moment from 'moment'
import 'moment/locale/zh-cn'
import update from 'react-addons-update'
import { myFetch, config } from '../utils'

moment.locale('zh-cn')
const Search =　Input.Search
const Option = Select.Option
const FormItem = Form.Item
const RadioGroup = Radio.Group
const DATE_FORMAT = config.dateFormat
const text = <span>请选择批量操作</span>

// 学员中一行搜素和按钮的组件
class IntentionChoice extends Component {
  constructor() {
    super()
    this.state = {
      startValue: null,
      endValue: null,
      endOpen: false,
      modal2Visible: false,
      value: 1,
      popoverVisible: false,
    }
    this.disabledStartDate = this.disabledStartDate.bind(this)
    this.disabledEndDate = this.disabledEndDate.bind(this)
    this.onChange = this.onChange.bind(this)
    this.onStartChange = this.onStartChange.bind(this)
    this.onEndChange = this.onEndChange.bind(this)
    this.handleStartOpenChange = this.handleStartOpenChange.bind(this)
    this.handleEndOpenChange = this.handleEndOpenChange.bind(this)
    this.onRadioChange = this.onRadioChange.bind(this)
    this.directorChange = this.directorChange.bind(this)
    this.needChange = this.needChange.bind(this)
    this.addCustomer = this.addCustomer.bind(this)
    this.search = this.search.bind(this)
  }
  disabledStartDate(startValue) {
    const endValue = this.state.endValue;
    if (!startValue || !endValue) {
      return false;
    }
    return startValue.valueOf() > endValue.valueOf();
  }

  disabledEndDate(endValue) {
    const startValue = this.state.startValue;
    if (!endValue || !startValue) {
      return false;
    }
    return endValue.valueOf() <= startValue.valueOf();
  }

  onChange(field, value) {
    this.setState({
      [field]: value,
    });
  }

  onStartChange(value) {
    this.onChange('startValue', value);
  }

  onEndChange(value) {
    this.onChange('endValue', value);
  }

  handleStartOpenChange(open) {
    if (!open) {
      this.setState({ endOpen: true });
    }
  }

  handleEndOpenChange(open) {
    this.setState({ endOpen: open });
  }

  setModal2Visible(modal2Visible) {
    this.setState({ modal2Visible });
  }

  onRadioChange(e) {
    console.log('radio checked', e.target.value);
    this.setState({
      value: e.target.value,
    })
  }
  directorChange(value) {
    console.log(`selected ${value}`);
  }

  needChange(value) {
    console.log(`selected ${value}`);
  }

  render() {
    const children = []
    for (let i = 10; i < 36; i++) {
      children.push(<Option key={i.toString(36) + i}>{i.toString(36) + i}</Option>)
    }
    const { common: { types, levels, sources, managers }, batchRemove } = this.props
    const { getFieldDecorator } = this.props.form
    const { startValue, endValue, endOpen, inputVisible, inputValue, tags, needTags, needValue, needVisible, popoverVisible  } = this.state
    const dateRules = {
      rules: [{ type: 'object', required: true, message: '请选择日期！' }],
    }
    const content = (
      <div>
        <p
          onClick={() => {
            this.setState({popoverVisible: false}, () => {
              batchRemove()
            })
          }}
        >
          删除
        </p>
      </div>
    )
    return (
        <div className="rt-intent-choice cl">
          <div className="lf">
            {getFieldDecorator('searchPhoneNumber')(
              <Search
                className="rt-intent-seach lf"
                placeholder="输入手机号搜素"
              />
            )}
            {getFieldDecorator('keyword')(
              <Search
                className="rt-intent-seach lf"
                placeholder="输入关键字"
              />
            )}
            <DatePicker
              className="lf"
              disabledDate={this.disabledStartDate}
              showTime
              format="YYYY-MM-DD"
              value={startValue}
              placeholder="开始日期YY-MM-DD"
              onChange={this.onStartChange}
              onOpenChange={this.handleStartOpenChange}
            />
            <span className="rt-date">至</span>
            <DatePicker
              disabledDate={this.disabledEndDate}
              showTime
              format="YYYY-MM-DD"
              value={endValue}
              placeholder="结束日期YY-MM-DD"
              onChange={this.onEndChange}
              open={endOpen}
              onOpenChange={this.handleEndOpenChange}
            />
            <Button
              className="rt-btn-search"
              onClick={this.search}
            >
              搜索
            </Button>
          </div>
          <div className="rf">
            <Button
              className="rt-btn-orange lf"
              icon="addfile"
              onClick={
                () => {
                  this.setState({
                    modal2Visible: true,
                  })
                }
              }
            >
              新建学员
            </Button>
            <Button className="rt-btn-greenBlue lf">学员导入</Button>
            <Popover visible={popoverVisible} placement="bottomRight" title={text} content={content} trigger="click" onVisibleChange={popoverVisible => this.setState({popoverVisible})}>
              <Button className="rt-btn-greenBlue lf">
                批量操作<Icon type="caret-down" />
              </Button>
            </Popover>
            {/*<Select
              className="rt-intent-sel lf"
              showSearch
              style={{ width: 86 }}
              placeholder="批量操作"
              optionFilterProp="children"
              filterOption={(input, option) => option.props.value.toLowerCase().indexOf(input.toLowerCase()) >= 0}
            >
              <Option value="add">增加</Option>
              <Option value="update">修改</Option>
              <Option value="del">删除</Option>
            </Select>*/}
          </div>
          <Modal
            title="新建学员"
            wrapClassName="vertical-center-modal"
            okText="保存"
            cancelText="取消"
            visible={this.state.modal2Visible}
            onOk={this.addCustomer}
            onCancel={() => this.setModal2Visible(false)}
          >
            <div className="cl ">
              <Button className="rt-btn-show rt-btn-bottom-active lf">学员详情</Button>
              <Button
                className="rt-btn-return rf"
                onClick={
                  () => {
                    this.setModal2Visible(false)
                  }
                }
              >
                返回列表
              </Button>
            </div>
            <div className="rt-stu-new">
              <Form inline className="rt-form-new">
                <FormItem
                  label="姓名"
                >
                  {getFieldDecorator('name', {
                    rules: [{required: true, message: '请填写姓名'}]
                  })(
                    <Input placeholder="请输入学员姓名" />
                  )}
                </FormItem>
                <FormItem className="rt-radio-stu">
                  {getFieldDecorator('genre', {initialValue: types[0] ? types[0]._id : ''})(
                    <RadioGroup>
                      {
                        types.map(v => (
                          <Radio key={v._id} value={v._id}>{v.name}</Radio>
                        ))
                      }
                    </RadioGroup>
                  )}
                </FormItem>
                <FormItem
                  label="电话"
                >
                {getFieldDecorator('mobile', {
                  rules: [{required: true, message: '请填写电话'}]
                })(
                  <Input placeholder="请输入学员电话" />
                )}
                </FormItem>
                <FormItem
                  label="邮箱"
                >
                {getFieldDecorator('email', {
                  rules: [{type: 'email', message: '请填写正确的邮箱地址'}]
                })(
                  <Input placeholder="请输入学员邮箱" />
                )}
                </FormItem>
                <FormItem
                  label="公司"
                >
                {getFieldDecorator('company')(
                  <Input />
                )}
                </FormItem>
                <FormItem
                  label="职位"
                >
                {getFieldDecorator('position')(
                  <Input />
                )}
                </FormItem>
                <FormItem
                  className="rt-source-select"
                  label="来源"
                >

                  {getFieldDecorator('source', {
                    // rules: [{required: true, message: '请选择来源'}]
                  })(
                    <Select placeholder="请选择来源">
                      {
                        sources.map(v => (
                          <Option key={v._id} value={v._id}>{v.name}</Option>
                        ))
                      }
                    </Select>
                  )}

                </FormItem>
                <FormItem
                  label="创建日期"
                >
                  {getFieldDecorator('newDate', dateRules)(
                    <DatePicker placeholder="请选择日期" />
                  )}
                </FormItem>
              </Form>
              <Form className="rt-form-level" inline>
                <FormItem
                  className="rt-stu-need"
                  label="需求"
                >
                {getFieldDecorator('need')(
                  <Select
                    tags
                    style={{ width: '100%' }}
                    onChange={this.needChange}
                    tokenSeparators={[',']}
                    className="rt-select-tag"
                  >
                    {children}
                  </Select>
                )}
                </FormItem>
                <FormItem
                  label="级别"
                  className="rt-stu-lev"
                >
                {getFieldDecorator('level')(
                  <Select placeholder="客户类型">
                    {
                      levels.map(v => (
                        <Option key={v._id} value={v._id}>{v.name}</Option>
                      ))
                    }
                  </Select>
                )}
                </FormItem>
              </Form>
              <Form inline className="rt-form-new">
                <FormItem
                  label="负责人"
                >
                  {getFieldDecorator('manager')(
                    <Select
                      tags
                      style={{ width: '100%' }}
                      className="rt-select-tag"
                      tokenSeparators={[',']}
                    >
                      {
                        managers.map(v => (
                          <Option key={v._id} value={v._id}>{v.username}</Option>
                        ))
                      }
                    </Select>
                  )}
                </FormItem>
                <FormItem
                  label="下次沟通"
                >
                  {getFieldDecorator('nextDate', dateRules)(
                    <DatePicker placeholder="请选择日期" />
                  )}
                </FormItem>
              </Form>
            </div>
          </Modal>
        </div>
      )
  }
  addCustomer() {
    const {
      form: { validateFields },
      common: { types, managers },
      formatCustomerRecord,
      newSuccCb,
    } = this.props
    validateFields((err, fieldsValue) => {
      if (err) {
        return
      }
      const data = {
        ...fieldsValue,
        phoneNumber: fieldsValue['mobile'],
        createdAt: fieldsValue['newDate'].format(DATE_FORMAT),
        nextAt: fieldsValue['nextDate'].format(DATE_FORMAT),
        demand: fieldsValue['need'] ? fieldsValue['need'].join(',') : '',
      }
      let record = Object.assign({}, data)
      record = formatCustomerRecord(record)
      if (record.manager && record.manager.length > 0) {
        const filteredArr = managers.filter(v => record.manager.includes(v._id))
        if (filteredArr.length > 0) {
          record.manager = filteredArr
        }
      }
      myFetch('/v1/customers', {method: 'POST', body: JSON.stringify(data)})
        .then(rs => {
          if (rs) {
            record._id = rs._id
            message.success('添加学员成功')
            this.setState({
              modal2Visible: false,
            }, () => {
              newSuccCb(record)
            })
          }
        })
    })
  }
  search() {
    const { form: { getFieldValue }, search } = this.props
    const { startValue, endValue } = this.state
    const phoneNumber = getFieldValue('searchPhoneNumber')
    const keyword = getFieldValue('keyword')
    search({
      phoneNumber,
      keyword,
      startAt: startValue ? startValue.startOf('day').format(config.dateFormat) : null,
      endAt: endValue ? endValue.startOf('day').format(config.dateFormat) : null
    })
  }
}

export default Form.create()(IntentionChoice)